package com.springboot.cloud.demos.producer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.cloud.demos.entity.param.CouponQueryParam;
import com.springboot.cloud.demos.entity.po.Coupon;
import com.springboot.cloud.demos.producer.dao.CouponMapper;
import com.springboot.cloud.demos.producer.service.ICouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@RefreshScope
public class CoponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

    @Value("${producer.coupon:123}")
    private String value;

    @Override
    @CacheEvict(value = "coupon",allEntries=true)
    public boolean add(Coupon coupon) {
        return this.save(coupon);
    }

    @Override
    @CacheEvict(value = "coupon", key = "#root.targetClass+'-'+#id")
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @CacheEvict(value = "coupon", key = "#root.targetClass+'-'+#coupon.id")
    public boolean update(Coupon coupon) {
        return this.updateById(coupon);
    }

    @Override
    @Cacheable(value = "coupon", key = "#root.targetClass+'-'+#id")
    public Coupon get(String id) {
        log.info("value:{}", value);
        return this.getById(id);
    }

    @Override
    public List<Coupon> query(CouponQueryParam couponQueryParam) {
        QueryWrapper<Coupon> queryWrapper = couponQueryParam.build();
        if(StringUtils.isNotEmpty(couponQueryParam.getLevelId())){
            queryWrapper.eq("level", couponQueryParam.getLevelId());
        }
        if(couponQueryParam.getValidStartTime()!=null){
            queryWrapper.ge("valid_start_time", couponQueryParam.getValidStartTime());
        }
        if(couponQueryParam.getValidEndTime()!=null){
            queryWrapper.le("valid_end_time", couponQueryParam.getValidEndTime());
        }
        queryWrapper.orderByDesc("created_time");
        return this.list(queryWrapper);
    }
}
